package GuiClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.util.Vector;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

import TamirsGui.CreateMsgToServer;
import TamirsGui.ServerMsg;

import clientCommunicationHandler.ClientServerMsgHandler;
import clientCommunicationHandler.UserInterfaceMsgHandler;

public class TelnetClient {
	ClientBootstrap bootstrap;
	ChannelFuture lastWriteFuture;
	Channel channel;

	public TelnetClient(String serverIp,int comunicationPort) throws Throwable{
		String host = serverIp;
		int port = comunicationPort;

		//Configure the client
		ClientBootstrap bootstrap = new ClientBootstrap
				(new NioClientSocketChannelFactory
						(Executors.newCachedThreadPool(), Executors.newCachedThreadPool()));

		//configure the pipe line factory
		bootstrap.setPipelineFactory(new TelnetClientPipelineFactory());

		//start the connection attempt
		ChannelFuture future = bootstrap.connect(new InetSocketAddress(host,port));

		//wait until the connection attempt succeeds or fails.
		channel = future.awaitUninterruptibly().getChannel();
		if(!future.isSuccess()){
			throw future.getCause();
////			future.getCause().printStackTrace();
//			bootstrap.releaseExternalResources();
//			return;
		}

		lastWriteFuture = null;

	}

	public void sendMessageToServer(String message){
		lastWriteFuture = channel.write(message);
		boolean wantToExit = this.checkIfExitMsg(message);
		if (wantToExit){
			channel.getCloseFuture().awaitUninterruptibly();
			this.closeConnection();
		}


	}
	private boolean checkIfExitMsg(String message) {
		int delimiterIndex = message.indexOf(ServerMsg.delimiter);
		String messageHeader = message.substring(0,delimiterIndex);
		boolean exit = messageHeader.equalsIgnoreCase("exit"); 
		return exit;
	}

	private void closeConnection(){
		//wait until all messages are flushed before closing the channel.


		{
			lastWriteFuture.awaitUninterruptibly();
		}


		//close the connection. Make sure the close operation ends
		//because all I/O operation are asynchronous in Netty
		channel.close().awaitUninterruptibly();

		//Shut down all thread pools to exit.
		bootstrap.releaseExternalResources();

	}


}
